//
//  NGHomeTableViewController.swift
//  NingguoForum
//
//  Created by zhengsw on 2020/11/12.
//  Copyright © 2020 zhengsw. All rights reserved.
//

import UIKit
import ESPullToRefresh
//类似于OC中的typedef
typealias sendValueClosure=()->Void
class NGHomeTableView: UIView, UITableViewDelegate, UITableViewDataSource {
    var viewController: UIViewController? = nil
    var tableView: NGHomeTable!
    var datas: NSMutableArray!
    var _currOffsetY:CGFloat!
    var canSlide:Bool!
    var page = 1
    //声明一个闭包
    var slideDragBlock:sendValueClosure?
    override init(frame: CGRect) {
        
        super.init(frame: frame)
        _currOffsetY = 0.0
        datas = NSMutableArray()
        canSlide = true
        self.backgroundColor = UIColor.gray
        datas = NSMutableArray(array: [[Any](),[Any](),[Any]()])
        
        tableView = NGHomeTable(frame: bounds, style: .plain)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.register(NGHomeListCell.classForCoder(), forCellReuseIdentifier: "cell")
        tableView.register(NGHomeListPicAdCell.classForCoder(), forCellReuseIdentifier: "adCell")
        tableView.register(NGHomeCircleCell.classForCoder(), forCellReuseIdentifier: "circleCell")
        tableView.tableFooterView = UIView()
        self.addSubview(tableView)
        tableView.reloadData()
        
        requestDatas()
        
        
        
        //修改 下拉 上拉刷新 文字提示
        var header: ESRefreshHeaderAnimator {
            get {
                let h = ESRefreshHeaderAnimator.init(frame: CGRect.zero)
                h.pullToRefreshDescription = "下拉刷新"
                h.releaseToRefreshDescription = "松开获取最新数据"
                h.loadingDescription = "下拉刷新..."
                return h
            }
        }
        
        var footer: ESRefreshFooterAnimator {
            get {
                let f = ESRefreshFooterAnimator.init(frame: CGRect.zero)
                f.loadingMoreDescription = "上拉加载更多"
                f.noMoreDataDescription = "数据已加载完"
                f.loadingDescription = "加载更多..."
                return f
            }
        }
        
        self.tableView.es.addPullToRefresh(animator: header) {
            self.reloadAction()
        }

        self.tableView.es.addInfiniteScrolling(animator: footer) {
            self.reloadMoreAction()
        }
        
    }
    
    func requestDatas() {

        //获取轮播图
        HttpManager.sharedInstance.getHomeCircle { [self] (successd:Array<HomeCircle>) in
            self.datas.replaceObject(at: 0, with: successd)
            self.tableView.reloadData()
        } fail: { (fail) in
            
        }
        
        HttpManager.sharedInstance.getHomeClassify(success: { [self] (successd:Array<HomeClassifyModel>) in
            self.datas.replaceObject(at: 1, with: successd)
            self.tableView.reloadData()
        }) { (fail) in
            
        }
        
        requestHomeList()
    }
    
    func requestHomeList() {
        let patameters = ["p":page];
        HttpManager.sharedInstance.getHomeList(patameter: patameters,  success: { (successd:Array<HomeListModel>) in
            self.tableView.es.stopPullToRefresh()
            self.tableView.es.stopLoadingMore()
            if successd.count == 0 {
                self.tableView.es.noticeNoMoreData()
                return
            }
            
            var array = NSMutableArray(array: self.datas[2] as! Array)
            if self.page == 1 {//第一页重置
                array = NSMutableArray()
            }
            array.addObjects(from: successd)
            self.datas.replaceObject(at: 2, with: array)
            self.tableView.reloadData()
            self.page += 1;
            
        }) { (fail) in
            
        }
    }
    
    func reloadMoreAction() {//上拉
        requestHomeList()
    }
    func reloadAction() {//下拉重置
        self.page = 1
        requestDatas()
    }
    
    func setDatas(dataSource: NSMutableArray) {

        datas = dataSource
        tableView.reloadData()
    }
    
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    deinit {
        
    }
    
    // MARK: - Table view data source

     func numberOfSections(in tableView: UITableView) -> Int {
        
        return datas.count
    }

     func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
         
         let array = datas[section] as! Array<Any>
         
         if section == 0 {
             return array.count > 0 ? 1 : 0
         }
         if section == 1 {
             return array.count > 0 ? 1 : 0
         }
         
         return array.count
    }

    
     func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

         if indexPath.section == 0 {
             
             let cell = tableView.dequeueReusableCell(withIdentifier: "circleCell", for: indexPath) as! NGHomeCircleCell
             cell.delegate = self
             let array = datas[indexPath.section] as! Array<HomeCircle>
             cell.setModel(datas: array)
             return cell
             
         }
         if indexPath.section == 1 {
             let cell = NGHomeListClassifyCell.init(style: .default, reuseIdentifier: "classifyCell")
             let array = datas[indexPath.section] as! Array<HomeClassifyModel>

             cell.setDatas(datas: array as NSArray)
             return cell
         }

        let array = datas[indexPath.section] as! Array<HomeListModel>
        let model = array[indexPath.row]
        
        if model._type == "pic_ad" {
            let cell = tableView.dequeueReusableCell(withIdentifier: "adCell", for: indexPath) as! NGHomeListPicAdCell
            cell.setModel(model: array[indexPath.row])
            return cell
        }

        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! NGHomeListCell
        cell.setModel(model: model)
        return cell


    }
    

     func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
         if indexPath.section == 0 {
             return 150
         }
         
         if indexPath.section == 1 {
             let itemWidth = (KSCREEN_WIDTH - 100) / 5
             return itemWidth * 2 + 30
         }
         
         let array = datas[indexPath.section] as! Array<HomeListModel>
         let model = array[indexPath.row]
         if model._type == "pic_ad" {
             return 150
         }
        return 120
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let vc = NGHomeDetailViewController()
        
        let array = datas[indexPath.section] as! Array<HomeListModel>
        let model = array[indexPath.row]
        
        var link = model.link
        if link.components(separatedBy: "https").count == 1{
            link = Config.requestAddress + link
        }
        
        vc.configUrl(link: link)
        viewController?.navigationController?.pushViewController(vc, animated: true)
    }
    
}

extension NGHomeTableView:UIScrollViewDelegate {
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        _currOffsetY = scrollView.contentOffset.y
    }
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
//        if !canSlide {
//            scrollView.contentOffset = CGPoint.init(x: 0, y: scrollView.contentOffset.y == 0 ?0:_currOffsetY)
//        }
//        _currOffsetY = scrollView.contentOffset.y
//        if scrollView.contentOffset.y<0 {
//            canSlide = false
//            scrollView.contentOffset = CGPoint.zero
//            //通知父视图
//            if (slideDragBlock != nil) {
//                self.slideDragBlock!()
//            }
//        } else {
//            canSlide = true
//        }
    }
}

extension NGHomeTableView: NGHomeCircleCellDelegate {
    func circleViewClick(model: HomeCircle) {
        let vc:NGHomeDetailViewController?  = NGHomeDetailViewController()
        vc!.configUrl(link:Config.requestAddress + model.link)
        viewController?.navigationController?.pushViewController(vc!, animated: true)
    }
}
